package io.renren.common.utils;

import org.dom4j.*;

import java.util.*;

public class XMLFormatUtil {
    /**
     * xml字符串转为map集合
     * @param xmlStr
     * @return
     */
    public static Map<String, Object> xmlToMap(String xmlStr){
        List<Map<String, String>> resultList = iterateWholeXML(xmlStr);
        Map<String, Object> retMap = new HashMap<>();
        for (Map<String, String> map : resultList) {
            for (String key : map.keySet()) {
                retMap.put(key, map.get(key));
            }
        }
        return retMap;
    }

    /**
     * 递归解析任意的xml 遍历每个节点和属性
     *
     * @param xmlStr
     */
    public static List<Map<String, String>> iterateWholeXML(String xmlStr) {
        List<Map<String, String>> list = new ArrayList<>();
        try {
            Document document = DocumentHelper.parseText(xmlStr);
            Element root = document.getRootElement();
            recursiveNode(root, list);
            return list;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 递归遍历所有的节点获得对应的值
     *
     * @param
     */
    private static void recursiveNode(Element root, List<Map<String, String>> list) {
        // 遍历根结点的所有孩子节点
        HashMap<String, String> map = new HashMap<>();
        for (Iterator iter = root.elementIterator(); iter.hasNext();) {
            Element element = (Element) iter.next();
            if (element == null)
                continue;
            // 获取属性和它的值
            for (Iterator attrs = element.attributeIterator(); attrs.hasNext();) {
                Attribute attr = (Attribute) attrs.next();
                if (attr == null)
                    continue;
                String attrName = attr.getName();
                String attrValue = attr.getValue();

                map.put(attrName, attrValue);
            }
            // 如果有PCDATA，则直接提出
            if (element.isTextOnly()) {
                String innerName = element.getName();
                String innerValue = element.getText();
                map.put(innerName, innerValue);
                list.add(map);
            } else {
                // 递归调用
                recursiveNode(element, list);
            }
        }
    }
    /**
     * 测试
     */
    public static void main(String[] args) {
        long time = new Date().getTime();
        String xmlStr = "<?xml version='1.0' encoding='UTF-8'?><OPERATION><HEAD><TIMESTAMP>20190621173338</TIMESTAMP><LOCATION>SHANGHAI</LOCATION></HEAD><BODY><OPERATORID>admin</OPERATORID><OPERATORIP>127.0.0.1</OPERATORIP><USERINFO><USERID>1</USERID><USERNAME>zhangsan</USERNAME><PASSWORD>123456</PASSWORD><MOBILE>11111111111</MOBILE></USERINFO></BODY></OPERATION>";
        Map<String, Object> xmlToMap = xmlToMap(xmlStr);
        Set<Map.Entry<String,Object>> entrySet = xmlToMap.entrySet();
        for (Map.Entry<String, Object> entry : entrySet) {
            System.out.println(entry.getKey()+"---"+entry.getValue());
        }
        System.out.println("执行时长："+ (System.currentTimeMillis() - time) + "ms");
    }
}
